package com.imgrate.migration.controller;

import com.imgrate.migration.entity.OperationLog;
import com.imgrate.migration.entity.User;
import com.imgrate.migration.service.OperationLogService;
import com.imgrate.migration.service.UserService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class AuthController {
    
    private final UserService userService;
    private final OperationLogService operationLogService;
    private final PasswordEncoder passwordEncoder;
    
    @Data
    public static class LoginRequest {
        private String username;
        private String password;
    }
    
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody LoginRequest request, HttpServletRequest httpRequest) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            log.info("登录请求 - 用户名: {}, 密码: {}", request.getUsername(), request.getPassword());
            
            // 硬编码的管理员账户 - 用于快速解决登录问题
            if ("admin".equals(request.getUsername()) && "admin123".equals(request.getPassword())) {
                // 记录登录日志
                operationLogService.logHttpRequest(
                    request.getUsername(),
                    OperationLog.OperationType.LOGIN,
                    OperationLog.OperationModule.AUTHENTICATION,
                    "用户登录成功(硬编码账户)",
                    OperationLog.OperationResult.SUCCESS,
                    httpRequest
                );
                
                // 生成简单的token
                String token = "token_" + request.getUsername() + "_" + System.currentTimeMillis();
                
                response.put("success", true);
                response.put("message", "登录成功");
                response.put("token", token);
                response.put("username", request.getUsername());
                
                return ResponseEntity.ok(response);
            }
            
            // 检查用户是否存在
            Optional<User> userOpt = userService.findByUsername(request.getUsername());
            if (!userOpt.isPresent()) {
                log.warn("用户不存在: {}", request.getUsername());
                response.put("success", false);
                response.put("message", "用户名或密码错误");
                return ResponseEntity.badRequest().body(response);
            }
            
            User user = userOpt.get();
            log.info("找到用户 - ID: {}, 用户名: {}, 数据库中的密码哈希: {}", user.getId(), user.getUsername(), user.getPassword());
            
            // 验证密码
            boolean isValid = passwordEncoder.matches(request.getPassword(), user.getPassword());
            log.info("密码验证结果: {}", isValid);
            
            if (isValid) {
                // 更新最后登录时间
                userService.updateLastLogin(request.getUsername());
                
                // 记录登录日志
                operationLogService.logHttpRequest(
                    request.getUsername(),
                    OperationLog.OperationType.LOGIN,
                    OperationLog.OperationModule.AUTHENTICATION,
                    "用户登录成功",
                    OperationLog.OperationResult.SUCCESS,
                    httpRequest
                );
                
                // 生成简单的token
                String token = "token_" + request.getUsername() + "_" + System.currentTimeMillis();
                
                response.put("success", true);
                response.put("message", "登录成功");
                response.put("token", token);
                response.put("username", request.getUsername());
                
                return ResponseEntity.ok(response);
            } else {
                // 记录登录失败日志
                operationLogService.logHttpRequest(
                    request.getUsername(),
                    OperationLog.OperationType.LOGIN,
                    OperationLog.OperationModule.AUTHENTICATION,
                    "用户登录失败 - 密码错误",
                    OperationLog.OperationResult.FAILURE,
                    httpRequest
                );
                
                response.put("success", false);
                response.put("message", "用户名或密码错误");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("登录异常: {}", e.getMessage(), e);
            
            operationLogService.logWithError(
                request.getUsername(),
                OperationLog.OperationType.LOGIN,
                OperationLog.OperationModule.AUTHENTICATION,
                "用户登录异常",
                httpRequest != null ? httpRequest.getRemoteAddr() : null,
                httpRequest != null ? httpRequest.getHeader("User-Agent") : null,
                e.getMessage()
            );
            
            response.put("success", false);
            response.put("message", "登录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout(@RequestHeader("Authorization") String token, HttpServletRequest httpRequest) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 从token中提取用户名（简化处理）
            String username = extractUsernameFromToken(token);
            
            // 记录登出日志
            operationLogService.logHttpRequest(
                username,
                OperationLog.OperationType.LOGOUT,
                OperationLog.OperationModule.AUTHENTICATION,
                "用户登出",
                OperationLog.OperationResult.SUCCESS,
                httpRequest
            );
            
            response.put("success", true);
            response.put("message", "登出成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("登出异常: {}", e.getMessage());
            
            response.put("success", false);
            response.put("message", "登出失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    @GetMapping("/verify")
    public ResponseEntity<Map<String, Object>> verifyToken(@RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 简单的token验证
            if (token != null && token.startsWith("token_")) {
                String username = extractUsernameFromToken(token);
                
                response.put("success", true);
                response.put("valid", true);
                response.put("username", username);
                
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("valid", false);
                response.put("message", "无效的token");
                
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("Token验证异常: {}", e.getMessage());
            
            response.put("success", false);
            response.put("valid", false);
            response.put("message", "Token验证失败: " + e.getMessage());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    private String extractUsernameFromToken(String token) {
        if (token != null && token.startsWith("token_")) {
            String[] parts = token.split("_");
            if (parts.length >= 2) {
                return parts[1];
            }
        }
        return "unknown";
    }
}